package gov.pbc.nn.kjgl.jfcr.handler;

import gov.pbc.nn.kjgl.entity.ComputerRoomApplyEntry;
import gov.pbc.nn.kjgl.jfcr.dao.ApplyEntryDao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.bstek.bdf2.core.context.ContextHolder;
import com.bstek.uflo.client.service.TaskClient;
import com.bstek.uflo.env.Context;
import com.bstek.uflo.model.ProcessInstance;
import com.bstek.uflo.process.handler.CountersignHandler;

/**
 * 集成hander接口，根据usersesult判断是否确认或者拒绝，
 * 
 * @author jack.zhao
 * 
 */
@Component("sh.CountersignHandler")
public class CountersignHandlerSH implements CountersignHandler {
	@Autowired
	@Qualifier(TaskClient.BEAN_ID)
	private TaskClient taskClient;

	@Autowired
	private ApplyEntryDao applyEntryDao;

	/**
	 * agree是要跳转传流程的名字，每一个人物处理人处理完任务，都从shenhere变量中进行删除
	 * 特别提示，最后一次审核不走handerl，所以要在pr里面判断
	 */
	@Override
	public boolean handle(Context context, ProcessInstance process) {

		// Integer result = (Integer)
		// context.getProcessService().getProcessVariable("users", process);
		List<String> users = (List<String>) context.getProcessService().getProcessVariable("shenheren", process);
		// Integer sp = (Integer)
		// context.getProcessService().getProcessVariable("sp", process);
		String businessId = process.getBusinessId();
		ComputerRoomApplyEntry computerRoomApplyEntry = this.applyEntryDao.get(businessId, ComputerRoomApplyEntry.class);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("agree", "驳回");
		map.put("reStart","申请人重新修改【"+computerRoomApplyEntry.getTitle()+"】");
		for (String u : users) {
			Integer userresult = (Integer) context.getProcessService().getProcessVariable(u, process);
			if (userresult != null) {
				if (userresult.equals(1)) {
					map.put("agree", "通过");
					users.remove(ContextHolder.getLoginUserName());
					map.put("shenheren", users);
					map.put(ContextHolder.getLoginUserName(), -1);
					context.getProcessService().saveProcessVariables(process.getId(), map);
					return true;
				} else if (userresult.equals(0)) {
					map.put("agree", "驳回");
					users.remove(ContextHolder.getLoginUserName());
					map.put("shenheren", users);
					map.put(ContextHolder.getLoginUserName(), -1);
					System.out.println(users);
					context.getProcessService().saveProcessVariables(process.getId(), map);
					return false;
				}
			}
		}
		return false;
	}
}
